package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.IgasYesOrNoEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.dao.BizTmpMapper;
import cc.rengu.redp.bizimpl.upmp.domain.BizTmp;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpRole;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpUserInfo;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Description;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 临时表Service
 *
 * @author zhangxu
 */
@Service("bizTmpService")
@DS("upmp")
@Slf4j
@Transactional(rollbackFor = Exception.class, readOnly = true)
public class BizTmpServiceImpl extends ServiceImpl<BizTmpMapper, BizTmp> implements IBizTmpService {
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpUserInfoService upmpUserInfoService;
    @Autowired
    private IUpmpRoleService upmpRoleService;
    @Autowired
    private IUpmpPrivilegeCheckService authPrivilegeCheckService;
    @Autowired
    private IUpmpMenuService upmpMenuService;

    /**
     * 根据主记录key查询明细记录 ，调用者根据表名再从结果集筛选对应表名的数据
     *
     * @param instId
     * @param masterKey
     * @return
     */
    @Override
    public List<BizTmp> getBizTmpByMasterKey(String instId, String masterKey) {
        LambdaQueryWrapper<BizTmp> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizTmp::getInstId, instId);
        wrapper.eq(BizTmp::getMasterKey, masterKey);
        wrapper.eq(BizTmp::getDetailFlag, "Y");
        return this.list(wrapper);
    }

    /**
     * 保存临时表，需要重新开启事务，否则会保存到原事务开启的数据源中
     *
     * @param tmp
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void saveTmp(BizTmp tmp) {
        this.save(tmp);
    }

    /**
     * 删除后插入
     *
     * @param tmp BizTmp
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void deleteAndInsert(BizTmp tmp) {
        this.baseMapper.deleteById(tmp.getRealId());
        saveTmp(tmp);
    }

    /**
     * 获取临时表映射实体
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public BizTmp getBizTmpDetail(String id) {
        return this.getById(id);
    }


    /**
     * 保存主记录到临时表，判断临时表是否有数据有则修改，无则新增
     *
     * @param entity
     * @param user
     * @param bizOpr
     * @param updateTime
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void saveBizTmp(Object entity, UpmpUserInfoVO user, String instId, String bizOpr, String updateTime,
                           String oprMenuId, String oprMenuName, String status, String auditStatus, String realId, String webNextUrl
            , String mchntNo, String mchntName, String termNo) throws RedpException {
        BizTmp tmp = this.baseMapper.selectById(realId);
        if (null == tmp) {
            tmp = new BizTmp();
        }

        String bizData = JSON.toJSONString(entity);
        if (bizData.length() > 12000) {
            throw new RedpException("业务数据过长，请联系管理员！");
        }
        String ename = entity.getClass().getAnnotation(TableName.class).value().toLowerCase();
        String cname = entity.getClass().getAnnotation(ApiModel.class).description();
        String bizData1;
        String bizData2 = "";
        String bizData3 = "";
        if (bizData.length() > 4000) {
            bizData1 = bizData.substring(0, 3999);
            bizData2 = bizData.substring(4000);
        } else {
            bizData1 = bizData;
        }
        if (bizData2.length() > 4000) {
            bizData2 = bizData2.substring(0, 3999);
            bizData3 = bizData.substring(8000);
        }
        tmp.setBizData1(bizData1);
        tmp.setBizData2(bizData2);
        tmp.setBizData3(bizData3);
        tmp.setBizOpr(bizOpr);
        tmp.setOprId(user.getId());
        tmp.setCreateTime(updateTime);
        tmp.setLastOprId(user.getId());
        tmp.setLastUpdateTime(updateTime);
        tmp.setOprMenuId(oprMenuId);
        tmp.setOprMenuName(oprMenuName);
        tmp.setOprTableCname(cname);
        tmp.setOprTableEname(ename);
        tmp.setManageInstId(user.getInstId());
        tmp.setInstId(instId);
        tmp.setBizStatus(status);
        tmp.setAuditStatus(auditStatus);
        tmp.setMchntNo(mchntNo);
        tmp.setMchntName(mchntName);
        tmp.setTermNo(termNo);
        if (StringUtils.isEmpty(tmp.getRealId())) {
            tmp.setRealId(realId);
        }
        tmp.setWebNextUrl(webNextUrl);
        this.save(tmp);
    }

    /**
     * 保存明细记录到临时表，判断临时表是否有数据有则修改，无则新增
     *
     * @param entity
     * @param user
     * @param bizOpr
     * @param updateTime
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void saveBizTmpDtl(Object entity, UpmpUserInfoVO user, String instId, String bizOpr, String updateTime,
                              String oprMenuId, String oprMenuName, String status, String auditStatus, String realId, String webNextUrl,
                              String detailFlag, String masterKey, String mchntNo, String mchntName, String termNo) throws RedpException {
        BizTmp tmp = this.baseMapper.selectById(realId);
        if (null == tmp) {
            tmp = new BizTmp();
        }

        String bizData = JSON.toJSONString(entity);
        int bizDataLength;
        try {
            bizDataLength = CommonUtils.strDBLength(bizData);
        } catch (Exception e) {
            throw new RedpException("获取数据库字符集失败");
        }
        if (bizDataLength > 12000) {
            throw new RedpException("业务数据过长，请联系管理员！");
        }
        String ename = entity.getClass().getAnnotation(TableName.class).value().toLowerCase();
        String cname = entity.getClass().getAnnotation(ApiModel.class).value();
        String bizData1;
        String bizData2 = "";
        String bizData3 = "";
        if (bizDataLength > 4000) {
            bizData1 = CommonUtils.getSubString(bizData, 0, 3999);
            bizData2 = CommonUtils.getSubString(bizData, 3999);
        } else {
            bizData1 = bizData;
        }
        int bizData2Length;
        try {
            bizData2Length = CommonUtils.strDBLength(bizData2);
        } catch (Exception e) {
            throw new RedpException("获取数据库字符集失败");
        }
        if (bizData2Length > 4000) {
            bizData2 = CommonUtils.getSubString(bizData2, 0, 3999);
            bizData3 = CommonUtils.getSubString(bizData, 7999);
        }
        tmp.setBizData1(bizData1);
        tmp.setBizData2(bizData2);
        tmp.setBizData3(bizData3);
        tmp.setBizOpr(bizOpr);
        tmp.setOprId(user.getId());
        tmp.setCreateTime(updateTime);
        tmp.setLastOprId(user.getId());
        tmp.setLastUpdateTime(updateTime);
        tmp.setOprMenuId(oprMenuId);
        tmp.setOprMenuName(oprMenuName);
        tmp.setOprTableCname(cname);
        tmp.setOprTableEname(ename);
        tmp.setManageInstId(user.getInstId());
        tmp.setInstId(instId);
        tmp.setBizStatus(status);
        tmp.setAuditStatus(auditStatus);
        tmp.setDetailFlag(detailFlag);
        if (StringUtils.isEmpty(tmp.getDetailFlag())) {
            tmp.setDetailFlag(IgasYesOrNoEnum.Yes.getType());
        }
        tmp.setMasterKey(masterKey);
        tmp.setMchntNo(mchntNo);
        tmp.setMchntName(mchntName);
        tmp.setTermNo(termNo);
        if (StringUtils.isEmpty(tmp.getRealId())) {
            tmp.setRealId(realId);
        }
        tmp.setWebNextUrl(webNextUrl);
        if (StringUtils.isEmpty(tmp.getRealId())) {
            tmp.setRealId(realId);
            this.save(tmp);
        } else {
            this.updateById(tmp);
        }
    }

    /**
     * 将页面的optFlag转换成bizOpr
     *
     * @param pageOptFlag
     * @return
     */
    @Override
    public String convertOptFlagToBizOpr(String pageOptFlag) {
        String bizOpr = "";
        PageOptFlagEnum[] optFlagEnums = PageOptFlagEnum.values();
        for (PageOptFlagEnum optFlagEnum : optFlagEnums) {
            if (pageOptFlag.equals(optFlagEnum.getType())) {
                bizOpr = optFlagEnum.getBizOpr();
                break;
            }
        }
        return bizOpr;
    }

    /**
     * 根据临时表业务数据字符串获取业务数据对象
     *
     * @param t BizTmp
     * @return
     */
    public <T> T getTempObjByBizTmp(BizTmp t, Class<T> clazz) {
        String data = new StringBuilder(t.getBizData1())
                .append(t.getBizData2() == null ? "" : t.getBizData2())
                .append(t.getBizData3() == null ? "" : t.getBizData3()).toString();
        return JSON.parseObject(data, clazz);
    }

    /**
     * 根据id查询临时表数据并返回业务表对应实体实例
     *
     * @param id
     * @param clazz
     * @param <T>
     * @return
     */
    @Override
    public <T> T getObjFromBizTmp(String id, Class<T> clazz) throws RedpException {
        BizTmp bizTmp = this.getById(id);
        if (Common.isBlank(bizTmp)) {
            log.error("根据id[" + id + "]没有找到指定类型[" + clazz.getName() + "]临时表数据！");
            throw new RedpException("根据id[" + id + "]没有找到指定类型[" + clazz.getName() + "]临时表数据！");
        }
        StringBuffer json = new StringBuffer(bizTmp.getBizData1());
        if (Common.isNotBlank(bizTmp.getBizData2())) {
            json.append(bizTmp.getBizData2());
        }
        if (Common.isNotBlank(bizTmp.getBizData3())) {
            json.append(bizTmp.getBizData3());
        }
        T temp = JSON.parseObject(json.toString(), clazz);
        return temp;
    }

    @Override
    @Transactional
    public void delete(String[] ids) {
        List<String> list = Arrays.asList(ids);
        this.baseMapper.deleteBatchIds(list);
    }

    @Override
    @Transactional
    public void delete(String id) {
        this.baseMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void delete(List<BizTmp> tmps) {
        List<String> list = new ArrayList<>();
        tmps.forEach(tmp -> list.add(tmp.getRealId()));
        this.baseMapper.deleteBatchIds(list);
    }

    /**
     * 根据主记录key及表名查询所有记录,并返回表对应实体实例的集合
     *
     * @param instId
     * @param masterKey
     * @return
     */
    @Override
    public <T> List<T> getBizTmpByInstIdAndMasterKeyAndEname(String instId, Class<T> clazz, String masterKey)
            throws RedpException {
        List<BizTmp> bizTmps = this.baseMapper.getBizTmpByInstIdAndMasterKeyAndEname(instId, clazz.getAnnotation(TableName.class).value().toLowerCase(), masterKey);
        List<T> datas = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(bizTmps)) {
            for (BizTmp bizTmp : bizTmps) {
                T data = null;
                try {
                    data = clazz.newInstance();
                } catch (InstantiationException e) {
                    log.error("message:" + e.getMessage() + ",cause:" + e.getCause());
                    throw new RedpException("message:" + e.getMessage() + ",cause:" + e.getCause());
                } catch (IllegalAccessException e) {
                    throw new RedpException("message:" + e.getMessage() + ",cause:" + e.getCause());
                }
                String json = "";
                if (null != bizTmp.getBizData1()) {
                    json += bizTmp.getBizData1();
                }
                if (null != bizTmp.getBizData2()) {
                    json += bizTmp.getBizData2();
                }
                if (null != bizTmp.getBizData3()) {
                    json += bizTmp.getBizData3();
                }
                data = JSON.parseObject(json, clazz);
                datas.add(data);
            }
        }
        return datas;
    }

    @Override
    public List<BizTmp> getBizTmpByInstIdAndMasterKeyAndEname(String instId, String oprTableEname, String masterKey) {
        LambdaQueryWrapper<BizTmp> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizTmp::getInstId, instId);
        wrapper.eq(BizTmp::getOprTableEname, oprTableEname);
        wrapper.eq(BizTmp::getMasterKey, masterKey);
        return this.list(wrapper);
    }

    /**
     * 根据商户号查询明细记录 ，调用者根据表名再从结果集筛选对应表名的数据
     *
     * @param mchntNo
     * @param oprTableEname
     * @return
     */
    @Override
    public List<BizTmp> getBizTmpByMchntCd(String mchntNo, String oprTableEname) {
        LambdaQueryWrapper<BizTmp> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizTmp::getMchntNo, mchntNo);
        wrapper.eq(BizTmp::getOprTableEname, oprTableEname);
        return this.list(wrapper);
    }

    /**
     * 删除指定商户数据,指定表数据
     *
     * @param mchntNo
     * @param tableName
     */
    @Override
    public void deleteBizTmpByMchntNo(String mchntNo, String tableName) {
        LambdaQueryWrapper<BizTmp> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizTmp::getMchntNo, mchntNo);
        wrapper.eq(BizTmp::getOprTableEname, tableName);
        this.baseMapper.delete(wrapper);
    }

    /**
     * 根据商户号查询明细记录
     *
     * @param mchntNo
     * @return
     */
    @Override
    public List<BizTmp> getBizTmpByMchntCd(String mchntNo) {
        LambdaQueryWrapper<BizTmp> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizTmp::getMchntNo, mchntNo);
        return this.list(wrapper);
    }

    /**
     * 新增、修改、删除临时表明细记录
     *
     * @param delBizTmplist    删除的list
     * @param newBizTmplist    新增的list
     * @param updateBizTmplist 修改的list
     */
    @Override
    public void mergeBizTmps(List<BizTmp> delBizTmplist, List<BizTmp> newBizTmplist, List<BizTmp> updateBizTmplist) throws RedpException {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                if (CollectionUtils.isNotEmpty(delBizTmplist)) {
                    delete(delBizTmplist);
                }
                if (CollectionUtils.isNotEmpty(newBizTmplist)) {
                    saveBatch(newBizTmplist);
                }
                if (CollectionUtils.isNotEmpty(updateBizTmplist)) {
                    updateBatchById(updateBizTmplist);
                }
            }
        });
    }

    /**
     * 当bizData1存放业务表的唯一索引的json串时，调用此方法可以查询该业务数据对应的临时表数据
     *
     * @param instId
     * @param oprTableEname
     * @param bizData1
     * @return
     * @throws RedpException
     */
    @Override
    public BizTmp getBizTmpByUniqueKey(String instId, String oprTableEname, String bizData1) throws RedpException {
        LambdaQueryWrapper<BizTmp> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizTmp::getInstId, instId);
        wrapper.eq(BizTmp::getOprTableEname, oprTableEname);
        wrapper.eq(BizTmp::getBizData1, bizData1);
        List<BizTmp> list = this.list(wrapper);
        if (Common.isNotBlank(list) && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public Map<String,Object> getBizTmp(String id, String instId) {
        UpmpUserInfo userInfo = upmpUserInfoService.findById(id);
        String orgCode = userInfo.getOrgCode();
        List<UpmpRole> userRoles = upmpRoleService.findUserRole(userInfo.getId());
        boolean superFlag = false;
        if (userRoles != null && userRoles.size() > 0) {
            for (UpmpRole role : userRoles) {
                if (role.getRoleCode().equals("ROLE_BANK_ADMIN") || role.getRoleCode().equals("ROLE_SUPER_USER")
                        || role.getRoleCode().equals("ROLE_SUPER_MAIN") || role.getRoleCode().equals("ROLE_SUPER_OPR")) {
                    superFlag = true;
                    break;
                } else {
                    superFlag = false;
                    break;
                }
            }
        }
        if (superFlag){
            List<Map> check = this.baseMapper.findSuperUserCountCheck(instId);
            Map<String, Object> map = new HashMap<>();
            map.put("list",check);
            return map;
        }else {
            List<Map> check = this.baseMapper.findUserCountCheck(orgCode, instId);
            Map<String, Object> map = new HashMap<>();
            map.put("list",check);
            return map;
        }

    }

    /**
     * 审核管理的分页
     *
     * @param request
     * @param bizTmp
     * @return
     */
    @Override
    public IPage<BizTmp> findPage(QueryRequest request, BizTmp bizTmp) throws RedpException {
        try {
            //获取当前登录人信息
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            LambdaQueryWrapper<BizTmp> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//            List<UpmpRole> userRoles = upmpRoleService.findUserRole(userId);
//            boolean flag = false;
//            for (UpmpRole role : userRoles) {
//                if (role.getRoleCode().equals("ROLE_BANK_ADMIN") || role.getRoleCode().equals("ROLE_SUPER_OPR")|| role.getRoleCode().equals("ROLE_SUPER_MAIN")|| role.getRoleCode().equals("ROLE_SUPER_USER") ) {
//                    flag = true;
//                }
//
//            }
            if (!StringUtils.isEmpty(bizTmp.getInstId())) {
                lambdaQueryWrapper.eq(BizTmp::getInstId, bizTmp.getInstId());
            } else {
                lambdaQueryWrapper.eq(BizTmp::getInstId, user.getInstId());
            }
            if (!StringUtils.isEmpty(bizTmp.getAuditStatus())) {
                lambdaQueryWrapper.eq(BizTmp::getAuditStatus, bizTmp.getAuditStatus());
            }
            if (!StringUtils.isEmpty(bizTmp.getMchntNo())) {
                lambdaQueryWrapper.like(BizTmp::getMchntNo, bizTmp.getMchntNo());
            }
            if (!StringUtils.isEmpty(bizTmp.getOprMenuName())) {
                lambdaQueryWrapper.eq(BizTmp::getOprMenuName, bizTmp.getOprMenuName());
            }
            List<String> inAuditStatus=Lists.newArrayList();
            inAuditStatus.add(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
            inAuditStatus.add(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType());
            inAuditStatus.add(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType());
            inAuditStatus.add(BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType());
            inAuditStatus.add(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());

            lambdaQueryWrapper.eq(BizTmp::getDetailFlag, 'N');
            lambdaQueryWrapper.eq(BizTmp::getMasterShowFlag, 'Y');
            lambdaQueryWrapper.in(BizTmp::getAuditStatus, inAuditStatus);
            lambdaQueryWrapper.orderByDesc(BizTmp::getLastUpdateTime);
            Page<BizTmp> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            Page<BizTmp> bizTmpPage = this.page(page, lambdaQueryWrapper);
            List<BizTmp> list = new ArrayList<>();
            for (BizTmp record : bizTmpPage.getRecords()) {

                if(Common.isNotBlank(record.getLastOprId())){
                    UpmpUserInfo userInfo = upmpUserInfoService.findById(record.getLastOprId());
                    if(Common.isNotBlank(userInfo)){
                        record.setLastOprId(userInfo.getNickName());
                        list.add(record);
                    }else{
                        list.add(record);
                    }
                }else{
                    list.add(record);
                }

            }
            return bizTmpPage.setRecords(list);

        } catch (Exception e) {
            String message = "获取信息失败";
            log.error(message);
            throw new RedpException(message);
        }
    }

    /**
     * 操作菜单列表
     *
     * @param q
     * @param request
     * @return
     */
    @Override
    public Map<String, Object> operMenuSelect2List(QueryRequest request, BizTmp bizTmp) {

        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        QueryWrapper<BizTmp> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DISTINCT OPR_MENU_NAME");
        if (Common.isNotBlank(bizTmp.getOprMenuName())) {
            queryWrapper.like("OPR_MENU_NAME", bizTmp.getOprMenuName());
        }

        if (user.isAdmin()) {
            if (Common.isBlank(bizTmp.getInstId())) {
                log.error("运营中心管理员新增数据必须先选择法人行！");
            }
        } else {
            bizTmp.setInstId(user.getInstId());
        }
        queryWrapper.eq("  INST_ID  ", bizTmp.getInstId());
        Page<BizTmp> page = new Page<>();
        SortUtil.handlePageSort(request, page, true);
        Page<BizTmp> bizTmpPage = this.page(page, queryWrapper);
        List<BizTmp> bizTmpList = bizTmpPage.getRecords();
        Map<String, Object> maps = new HashMap<String, Object>();
        Map<String, String> map = new HashMap<String, String>();
        List<Object> list = new ArrayList<Object>();
        for (int i = 0; i < bizTmpList.size(); i++) {
            map = new HashMap<String, String>();
            map.put("name", bizTmpList.get(i).getOprMenuName());
            map.put("id", bizTmpList.get(i).getOprMenuName());
            list.add(map);
        }

        maps.put("rows", list);
        maps.put("more", false);
        return maps;
    }

    @Override
    public Map<String, Object> userCheckPrivilege(String bizTmpId, String userId) throws RedpException {
        Map<String, Object> result = new HashMap<>();
        List<UpmpRole> userRoles = null;
        UpmpUserInfo userInfo = null;
        String message = null;
        String code = BusinessContainer.SUCCESS;
        try {
            userRoles = upmpRoleService.findUserRole(userId);
            userInfo = upmpUserInfoService.findById(userId);
            if (userRoles == null || userInfo == null) {
                message = "当前登录用户没有审核权限";
                code=BusinessContainer.ERROR;
                log.info(message);
                throw new RedpException(message);

            }
            if (userRoles != null && userRoles.size() > 0) {
                for (UpmpRole role : userRoles) {
                    if (!role.getRoleCode().equals("ROLE_BANK_ADMIN") || !role.getRoleCode().equals("ROLE_SUPER_USER")
                            || !role.getRoleCode().equals("ROLE_SUPER_MAIN") || !role.getRoleCode().equals("ROLE_SUPER_OPR")) {
                        message = "当前登录用户没有审核权限";
                        code=BusinessContainer.ERROR;
                        log.info(message);
                        throw new RedpException(message);
                    }
                }
            } else {
                message = "当前登录用户没有审核权限";
                code=BusinessContainer.ERROR;
                log.info(message);
                throw new RedpException(message);
            }

            BizTmp bizTmp = this.getById(bizTmpId);
            if (bizTmp != null && !StringUtils.isEmpty(bizTmp.getLastOprId())) {
                String oprId = bizTmp.getLastOprId();
                //自己不能审批自己的数据
                if (oprId.equals(userInfo.getId()) || oprId.equals(userInfo.getUserName()) || oprId.equals(userInfo.getLoginId())) {
                    message = "登录用户不能审批自己创建的数据";
                    code=BusinessContainer.ERROR;
                    log.info(message);
                    throw new RedpException(message);
                }
            } else {
                message = "没有相关审核数据";
                code=BusinessContainer.ERROR;
                log.info(message);
                throw new RedpException(message);
            }
        } catch (Exception e) {
            log.info("userRoles或者userInfo为空");
        }
        //校验权限
//        UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(userInfo.getInstId(), "bizTmp:check");
//        if (privilegeCheck == null) {
//            String message = "当前登录用户没有审核权限";
//            log.info(message);
//            throw new RedpException(message);
//        }
        result.put("message", message);
        result.put("code", code);
        return result;
    }

    /**
     * 获取审核跳转的URL
     *
     * @param bizTmpId
     * @param userId
     * @return
     */
    @Override
    public String getCheckUrl(String bizTmpId, String userId) {
        BizTmp tmp = this.getById(bizTmpId);
        String url = tmp.getWebNextUrl();
//        String[] menuName = tmp.getOprMenuName().split(":");
//        String URL = upmpMenuService.findMenuUrl(menuName[1]);
        return url;
    }


}
